package snail.controllers;

import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.*;
import org.hibernate.Session;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import snail.data.CategoryDAO;
import snail.data.UserDAO;
import snail.hibernate.util.HibernateUtil;
import snail.misc.PreparedModelAndView;
import snail.model.Category;
import snail.model.User;

public class AdminController extends MultiActionController {

    @Override
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // Man ska inte kunna nå sidan om man inte är inloggad som admin
        User admin = (User) request.getSession().getAttribute("user");
        if (admin == null) {
            return new UserController().login(request, response, "../admin/");

        } else {
            if (admin.isAdmin() == false) {
                return new UserController().login(request, response, "../admin/");
            }
        }
        return super.handleRequest(request, response);
    }

    public ModelAndView index(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new PreparedModelAndView("admin/index", request);
        return mv;
    }

    public ModelAndView listUsers(HttpServletRequest request, HttpServletResponse response) {

        ModelAndView mv = new PreparedModelAndView(request);
        List<User> users = new UserDAO().getAll();
        mv.addObject("users", users);
        return mv;
    }

    public ModelAndView deleteUser(HttpServletRequest request, HttpServletResponse response) {

        if (request.getParameter("userId") != null) {
            int id = Integer.parseInt(request.getParameter("userId"));

            new UserDAO().deleteUser(id);
        }

        try {
            response.sendRedirect("listUsers");
        } catch (IOException ex) {
            Logger.getLogger(AdminController.class.getName()).log(Level.SEVERE, null, ex);
        }

        return null;

    }

    public ModelAndView categories(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new ModelAndView();

        List<Category> categories = new CategoryDAO().getAll();

        mv.addObject("categories", categories);

        return mv;
    }

    public ModelAndView editCategory(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new PreparedModelAndView(request);

        if (request.getMethod().equals("POST")) {

            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            System.out.println("jeasad");
            String name = request.getParameter("name");
            String description = request.getParameter("description");
            int parent = Integer.parseInt(request.getParameter("parent"));
            int id = Integer.parseInt(request.getParameter("id"));
            CategoryDAO cDao = new CategoryDAO();
            Category cat = cDao.getById(id);
            cat.setName(name);
            cat.setDescription(description);
            cat.setParentCategory(new CategoryDAO().getById(parent));
            cDao.flush();

            session.getTransaction().commit();

            try {
                response.sendRedirect("categories");
            } catch (IOException ex) {
                Logger.getLogger(AdminController.class.getName()).log(Level.SEVERE, null, ex);
            }
        }


        if (request.getParameter("categoryId") != null) {
            int id = Integer.parseInt(request.getParameter("categoryId"));
            Category c = new CategoryDAO().getById(id);
            mv.addObject("category", c);
        }
        
        return mv;

    }

    public ModelAndView deleteCategory(HttpServletRequest request, HttpServletResponse response) {

        if (request.getParameter("categoryId") != null) {
            int id = Integer.parseInt(request.getParameter("categoryId"));

            new CategoryDAO().deleteCategory(id);
        }
        try {
            response.sendRedirect("categories");
        } catch (IOException ex) {
            Logger.getLogger(AdminController.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    public ModelAndView createCategory(HttpServletRequest request, HttpServletResponse response) throws IOException {

        if (request.getMethod().equals("POST")) {

            String name = request.getParameter("name");
            String parentIdString = (request.getParameter("parentCategory"));
            String desc = request.getParameter("description");

            if (!name.equals("") && !desc.equals("")) {
                Category c = new Category();
                c.setName(name);

                c.setDescription(desc);
                if (!parentIdString.equals("noParent")) {
                    Category parent = new CategoryDAO().getById(Integer.parseInt(parentIdString));
                    c.setParentCategory(parent);
                }

                Session session = HibernateUtil.getSessionFactory().getCurrentSession();
                session.save(c);

                response.sendRedirect("categories");
            }
        }

        PreparedModelAndView mv = new PreparedModelAndView(request);
        return mv;


    }
}
